<template>
  <div class="balance">
    <my-tabs :tab-list="tabList">
      <template v-slot="{ row }">
        <li
          class="item pointer"
          :class="{ active: routePath === row.path }"
          @click="handleClickMenu(row)"
        >
          {{ row.title }}
        </li>
      </template>
    </my-tabs>
    <el-row type="flex" justify="space-between" align="middle" class="balance-money">
      <div class="left">
        <span class="text">账户余额</span>
        <span class="money">{{ balance == '' ? 0 : balance | formatMoney }}</span>
      </div>
      <!-- <el-input placeholder="输入充值卡卡号" size="mini" v-model="exchangeVal" class="input">
        <template slot="append">
          <el-button size="mini">充值</el-button>
        </template>
      </el-input> -->
    </el-row>
    <div class="balance-recharge">
      <div class="balance-title">充值</div>
      <el-radio-group v-model="balanceRechargeId" @change="changeRecharge">
        <el-row type="flex" class="recharge">
          <el-radio
            class="item"
            :label="item.id"
            border
            v-for="(item, index) in recharge.public"
            :key="index"
          >
            <div class="fill">充{{ item.balance | formatMoney('元') }}</div>
            <div class="send" v-if="item.give_balance != 0">
              送{{ item.give_balance | formatMoney('元') }}
            </div>
          </el-radio>
          <el-input
            class="item input"
            maxlength="5"
            minlength="1"
            v-model="balanceRenminbi"
            @input="blurText"
            placeholder="请输入充值金额"
            prefix-icon="edu-icon-fl-renminbi"
          ></el-input>
        </el-row>
      </el-radio-group>
      <div class="msg">注：充值到余额后不能再转至银行卡或支付宝，充值比例为{{ proportion }}</div>
    </div>
    <div class="balance-choose">
      <div class="balance-title">支付方式</div>
      <edu-payment-choose
        :paymentList="payway"
        :payment="payVal"
        :value.sync="payVal"
      ></edu-payment-choose>
    </div>
    <el-row type="flex" align="middle" justify="space-between" class="balance-deal">
      <div class="checked">
        <el-checkbox v-model="checked">我已阅读并同意</el-checkbox>
        <el-link type="primary" :underline="false" @click="handleKeyword('payment')"
          >《{{ getAgreementTitle('payment') }}》</el-link
        >
      </div>
      <el-row type="flex" align="middle" class="money">
        <div class="text">支付金额：</div>
        <div class="num">¥{{ balanceRenminbi != '' ? price : balanceRechargePrice }}</div>
      </el-row>
    </el-row>
    <el-row type="flex" align="middle" justify="end">
      <el-button type="primary" @click="handleBalance" :loading="disabledButton"
        >立即充值</el-button
      >
    </el-row>
  </div>
</template>

<script>
import projectSetting from '@/settings/projectSetting.js'
import payment from '@/utils/payment.js'
import MyTabs from '../components/myTab.vue'
import EduPaymentChoose from '@/components/EduPaymentChoose'
import { mapGetters } from 'vuex'
export default {
  components: {
    MyTabs,
    EduPaymentChoose
  },
  inject: ['reload'],
  data() {
    return {
      tabList: [
        {
          path: '/my/finance/my_balance',
          title: '我的余额'
        },
        {
          path: '/my/finance/balance_flow',
          title: '余额流水'
        }
      ],
      balance: 0, // 余额
      recharge: {}, // 充值
      payway: [], // 支付方式
      payVal: '', // 支付方式
      proportion: '', // 比例
      balanceRechargeId: 0,
      balanceRechargePrice: 0,
      balanceRenminbi: '',
      exchangeVal: '',
      checked: true,
      qrcodeVal: '',
      dialogVisible: false,
      disabledButton: false
    }
  },
  computed: {
    ...mapGetters({
      getAgreementTitle: 'projectSetting/getAgreementTitle'
    }),
    price() {
      return this.handlewo()
    },
    routePath() {
      return this.$route.path
    }
  },
  mounted() {
    this.getBalance()
  },
  methods: {
    // 请求余额
    getBalance() {
      this.$api.getBalance(res => {
        this.balance = res.data.balance
        this.recharge = res.data.recharge
        this.balanceRechargeId = res.data.recharge.public[0].id
        this.balanceRechargePrice = res.data.recharge.public[0].price
        this.proportion = res.data.recharge.ratio
        this.payway = this.changeSort(res.data.payway)
        const list = ['wxpay', 'alipay']
        const val = list.find(k => this.payway.includes(k))
        this.payVal = val || ''
      })
    },
    changeSort(arr) {
      const order = ['wxpay', 'alipay']
      const set1 = new Set(arr)
      const set2 = new Set(order)
      const intersection = [...set1].filter(x => set2.has(x))
      intersection.sort((a, b) => {
        return order.indexOf(a) - order.indexOf(b)
      })
      return intersection
    },
    changeRecharge() {
      this.balanceRenminbi = ''
      this.recharge.public.forEach(element => {
        if (this.balanceRechargeId == element.id) {
          this.balanceRechargePrice = element.price
        }
      })
    },
    // 充值提交
    handleBalance() {
      if (this.checked) {
        if (this.payVal == '') return
        this.disabledButton = true
        this.$api.createBalanceOrder(
          {
            from: projectSetting.globDeviceType,
            recharge_id: this.balanceRenminbi == '' ? this.balanceRechargeId : '0',
            payment: this.price,
            balance: this.balanceRenminbi == '' ? this.balanceRechargePrice : this.balanceRenminbi
          },
          res => {
            payment.handlePaymentSubmit(
              res.data.order_no,
              this.payVal,
              '/my/finance/my_balance',
              res => {
                this.reload()
              }
            )
            setTimeout(() => {
              this.disabledButton = false
            }, 300)
          },
          error => {
            this.$message.error(error.msg)
            this.disabledButton = false
          }
        )
      } else {
        this.$message.warning('阅读并同意' + this.getAgreementTitle('payment'))
      }
    },
    // 自定义输入充值金额通用比例计算 - 保留两位小数
    handlewo() {
      /**
       * 比例 1:2
       * 实际到账 =  (输入金额 / 2) * 1
       */
      let num = 0
      let pop = this.proportion.split(':')
      num = ((this.balanceRenminbi / pop[1]) * pop[0]).toFixed(2)
      return num
    },
    // 输入金额为自然数
    blurText(e) {
      let boolenan = new RegExp('^[0-9]([0-9])*$').test(this.balanceRenminbi)
      if (!boolenan) {
        this.balanceRenminbi = ''
      }
    },
    handleKeyword(key) {
      this.$router.push({
        path: '/agreement/' + key
      })
    },
    handleClickMenu(data) {
      this.$router.push({
        path: data.path
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.balance {
  .balance-money {
    .left {
      font-size: 16px;
      .text {
        color: $text-color-import;
      }
      .money {
        color: $text-color-price;
      }
    }
    .input {
      width: 200px;
      ::v-deep .el-input-group__append {
        color: #fff;
        padding: 0 15px;
        @include edu-color-primary(border-color);
        @include edu-color-primary(background-color);
      }
    }
  }
  .balance-title {
    font-size: 14px;
    color: $text-color-import;
  }
  .balance-recharge {
    margin-top: 25px;
    .recharge {
      flex-wrap: wrap;
      width: 590px;
      .item {
        margin-right: 12px;
        margin-top: 10px;
        &.el-radio {
          margin-right: 12px;
        }
        &.el-radio.is-bordered {
          + .el-radio.is-bordered {
            margin-left: 0;
          }
          width: 106px;
          height: 50px;
          padding: 0;
          position: relative;
          border-radius: 0;
          ::v-deep .el-radio__input {
            position: absolute;
            opacity: 0;
            top: 0;
          }
          ::v-deep .el-radio__label {
            height: 100%;
            padding-left: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
          }
          .fill {
            font-size: 15px;
            color: $text-color-secondary;
            margin-bottom: 2px;
          }
          .send {
            font-size: 12px;
            color: #b7bac1;
          }

          .el-radio__input.is-checked + .el-radio__label .fill,
          .el-radio__input.is-checked + .el-radio__label .send {
            @include edu-color-auxiliary;
          }
        }
      }
      .input {
        flex: 1;
        ::v-deep .el-input__inner {
          height: 50px;
          line-height: 50px;
          border-radius: 0;
        }
        ::v-deep .el-input__prefix {
          font-size: 18px;
          color: $text-color-secondary;
        }
      }
    }
    .msg {
      color: #b7bac1;
      font-size: 12px;
      margin-top: 8px;
    }
  }
  .balance-choose {
    margin-top: 35px;
  }
  .balance-deal {
    margin-top: 40px;
    margin-bottom: 20px;
    .money {
      .text {
        font-size: 13px;
        font-weight: 400;
        color: $text-color-auxiliary;
      }
      .num {
        font-size: 20px;
        color: $text-color-price;
      }
    }
  }
}
</style>
